package cn.tedu.management.portal.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Override //配置身份验证
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override //配置访问控制
    protected void configure(HttpSecurity http) throws Exception {
        // 登录页面的URL
        String loginUrl = "/login.html";
        // 处理登录表单的URL
        String loginProcessingUrl = "/login";
        // 不需要登录即可请求的URL（白名单）
        String[] urls = {
                loginUrl,
                loginProcessingUrl
//                "/register.html",
//                "/portal/user/register/student",
//                "/browser_components/**",
//                "/css/**",
//                "/img/**",
//                "/js/**",
//                "npm/**",
//                "/favicon.ico",
//                "/package-lock.json"
        };

        // authorizeRequests()：对请求进行验证
        // antMatchers()：设置请求路径
        // permitAll()：直接许可，即不需要验证
        // anyRequest()：除了此前配置过的URL以外的所有请求
        // authenticated()：必须已经验证
        // formLogin()：通过登录表单来验证用户登录

        http.authorizeRequests()
                .antMatchers(urls).permitAll()
                .anyRequest().authenticated();

        //设置登录的页面 不使用security框架自带的登录页面
        http.formLogin()
                .loginPage(loginUrl)
                .loginProcessingUrl(loginProcessingUrl);

        http.csrf().disable();//禁止跨域攻击

    }
}
